package sdp.group14.management;

import static sdp.group14.appdata.HousingSQLiteOpenHelper.*;
import sdp.group14.appdata.HousingSQLiteOpenHelper;
import sdp.group14.appdata.Request;

import java.util.ArrayList;

import android.app.Application;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

/**
 * this class is to connect the database and operate all the
 * data reading, writing function between the database and 
 * the list view adapter
 * @author ste706
 *
 */
public class HousingManagerApplication extends Application {

	private SQLiteDatabase database;
	private ArrayList<Request> currentRequests;

	/** Called when the activity is first created. */
	@Override
	public void onCreate() {
		super.onCreate();
		Log.i("database", "loading database");
		HousingSQLiteOpenHelper helper = new HousingSQLiteOpenHelper(this);
		database = helper.getWritableDatabase();
		if (null == currentRequests) {
			loadRequests();
		}
	}

	/**
	 * close the database when the application is terminated
	 */
	@Override
	public void onTerminate() {
		database.close();
		super.onTerminate();
	}

	/**
	 * set the Requests equals to the given Requests array
	 * @param currentRequests
	 */
	public void setCurrentRequests(ArrayList<Request> currentRequests) {
		this.currentRequests = currentRequests;
	}

	/**
	 * get all the Requests in the Requests array
	 * @return
	 */
	public ArrayList<Request> getCurrentRequests() {		
		return currentRequests;
	}

	public Request getRequestById(long id)
	{
		int i = 0;
		for(int j=0; j<currentRequests.size();j++)
		{
			if(currentRequests.get(j).getReqID()==id)
				i = j;
		}
		return currentRequests.get(i);
	}

	public int getRequestPosition(Request request)
	{
		for(int j=0; j<currentRequests.size();j++)
		{
			if(currentRequests.get(j).getReqID() == request.getReqID())
				return j;
		}
		return -1;
	}

	/**
	 * add the Request to the database
	 * @param t
	 */
	public void addRequest(Request r) {
		assert(null != r);

		ContentValues values = new ContentValues();
		values.put(REQUEST_DATE, r.getreqDate());
		values.put(REQUEST_STATUS, r.getreqStatus());
		values.put(REQUEST_CATEGORY, r.getreqCategory());
		values.put(REQUEST_CAUSE, r.getreqCause());
		values.put(REQUEST_DESCRIPTION, r.getreqDescription());
		values.put(REQUEST_COMMENT, r.getreqComment());
		values.put(REQUEST_ALLOW_ENTER, r.isReqAllowEnter());
		r.setReqID(database.insert(REQUESTS_TABLE, null, values));
		Log.e("database",""+r.getReqID());
		currentRequests.add(r);
	}


	/**
	 * update the Request to the database
	 * @param t
	 */
	public void updateRequest(Request r) {
		assert(null != r);

		try
		{
			ContentValues values = new ContentValues();
			values.put(REQUEST_DATE, r.getreqDate());
			values.put(REQUEST_STATUS, r.getreqStatus());
			values.put(REQUEST_CATEGORY, r.getreqCategory());
			values.put(REQUEST_CAUSE, r.getreqCause());
			values.put(REQUEST_DESCRIPTION, r.getreqDescription());
			values.put(REQUEST_COMMENT, r.getreqComment());
			values.put(REQUEST_ALLOW_ENTER, r.isReqAllowEnter());
			String filter = "" +  REQUEST_ID + "="+ r.getReqID();
			database.update(REQUESTS_TABLE, values,filter, null);
			//insert(REQUESTS_TABLE, null, values));
			Log.e("database","update requestID:"+r.getReqID());
			currentRequests.set(getRequestPosition(r), r);
		}
		catch(Exception e)
		{
			Log.e("database","error occurs in updating request");
		}
	}

	/**
	 * delete the given Request in the database
	 */
	public void deleteRequest(Long id) {
		try
		{
		String where = String.format("%s == (%s)", REQUEST_ID, id);
		database.delete(REQUESTS_TABLE, where, null);
		}
		catch(Exception e)
		{
			Log.e("database", "errors occured in deleting request");
		}
	}

	/**
	 * delete all the Requests in the database
	 */
	public void deleteAllRequests()
	{
		database.delete(HousingSQLiteOpenHelper.REQUESTS_TABLE, null, null);
	}

	/**
	 * save all the Requests in the Requests array into the database
	 * @param t
	 */
	public void saveRequest(Request r) {
		assert(null != r);
		ContentValues values = new ContentValues();
		values.put(REQUEST_DATE, r.getreqDate());
		values.put(REQUEST_STATUS, r.getreqDate());
		values.put(REQUEST_CATEGORY, r.getreqDate());
		values.put(REQUEST_DESCRIPTION, r.getreqDate());
		values.put(REQUEST_COMMENT, r.getreqDate());
		values.put(REQUEST_ALLOW_ENTER, r.getreqDate());	
		long id = r.getReqID();
		String where = String.format("%s = %d", REQUEST_ID, id);

		database.update(REQUESTS_TABLE, values, where, null);
	}	

	/**
	 * load all the Requests from database when the application is
	 * first initialized
	 */	
	private void loadRequests() {
		try
		{

			Log.i("database", "loading tasks");
			currentRequests = new ArrayList<Request>();
			Cursor requestCursor = database.query(REQUESTS_TABLE, new String[]{REQUEST_ID, REQUEST_DATE, REQUEST_STATUS, REQUEST_CATEGORY, REQUEST_DESCRIPTION, REQUEST_CAUSE, REQUEST_COMMENT, REQUEST_ALLOW_ENTER },  null, null, null, null, String.format("%s,%s", REQUEST_DATE, REQUEST_ID));
			requestCursor.moveToFirst();
			Request r;
			if(!requestCursor.isAfterLast()){
				do{
					int reqId = requestCursor.getInt(0);
					String reqDate = requestCursor.getString(1);
					String reqCategory = requestCursor.getString(3);
					String reqStatus = requestCursor.getString(2);
					String reqDescription = requestCursor.getString(4);
					String reqComment = requestCursor.getString(6);
					String reqCause = requestCursor.getString(5);
					int reqAllowEnter = requestCursor.getInt(7);

					r = new Request(reqDate, reqStatus, reqCategory, reqDescription, reqComment,  reqCause, reqAllowEnter);
					r.setReqID(reqId);			
					currentRequests.add(r);
				}
				while(requestCursor.moveToNext());
			}

			requestCursor.close();
		}
		catch (Exception e)
		{
			Log.e("database",e.getMessage());
		}		
	}
}
